package cn.lger.icollege.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibeetl.starter.BeetlTemplateCustomize;
import com.ibeetl.starter.ObjectMapperJsonUtil;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.ext.simulate.JsonUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * Code that Changed the World
 * Pro said
 * Created by Pro on 2018-05-05.
 */
@Configuration
public class CustomerBeetl {

    @Resource
    private JsonUtil jsonUtil;

    @Bean
    public JsonUtil getJsonUtil() {
        return new ObjectMapperJsonUtil(new ObjectMapper());
    }


    @Bean
    public BeetlTemplateCustomize config() {
        return groupTemplate -> groupTemplate.registerFunction("toJson", new toJson());
    }

    class toJson implements Function {

        @Override
        public Object call(Object[] objects, Context context) {
            Object o = objects[0];
            if (o != null) {
                try {
                    context.byteWriter.write(jsonUtil.toJson(o).getBytes("UTF-8"));
                } catch (Exception e) {
                    throw new RuntimeException("json格式化异常", e);
                }
            }
            return null;
        }
    }

}
